"""
@Author    : ghenyar
@Time      : 2025/9/3 16:43
@File      : system_service
@Desc      : 系统
"""
import os
from datetime import datetime
from pathlib import Path
from packaging import version
from sqlalchemy.ext.asyncio import AsyncSession

from app.admin.schemas.admin import AdminLogSerialize
from app.admin.schemas.settings import Agreement
from app.common.page_result import PageResult
from app.enum.agreement import AgreementType, AgreementStatus
from app.enum.oss_list import OSSList
from app.libs.oss_file import StorageFile

from app.common.model_querier import ModelQuerier
from app.models import ConfigsModel, AgreementModel
from app.models.admin_model import AdminLogModel
from app.utils.log import LoggingUtil


class SystemService:
    logger = LoggingUtil(f"{__name__}.SystemService")

    @classmethod
    def handel_storage_file(cls, file_path: str, config: dict):
        # 后台进行远程上传
        storage = StorageFile(config)
        if storage.chunked_file_upload(file_path):
            # 远程上传完后进行删除临时文件
            os.remove(file_path)
        else:
            file_name = Path(file_path).name
            cls.logger.error("文件{}上传失败！".format(file_name))

    @classmethod
    async def log_lists(cls, db: AsyncSession, page: int, pageSize: int, start_time: int = None, end_time: int = None,
                        key: str = None,
                        types: int = None) -> PageResult:
        """
        操作日记列表
        :param db:
        :param page:
        :param pageSize:
        :param start_time:
        :param end_time:
        :param key:
        :param types:
        :return:
        """
        # 构建查询条件
        conditions = []

        if key:
            conditions.append(AdminLogModel.account.contains(key))
        if types == 0:
            conditions.append(AdminLogModel.types == 0)
        else:
            conditions.append(AdminLogModel.types != 0)

        # 时间查询条件
        if start_time and end_time:
            start_datetime = datetime.fromtimestamp(start_time / 1000).replace(hour=0, minute=0, second=0)
            end_datetime = datetime.fromtimestamp(end_time / 1000).replace(hour=23, minute=59, second=59)

            # 大于等于开始时间 、小于等于结束时间
            conditions.append(AdminLogModel.created_at >= start_datetime)
            conditions.append(AdminLogModel.created_at <= end_datetime)

        querier = ModelQuerier(db, AdminLogModel)
        if conditions:
            querier = querier.where(*conditions)

        logs_list = await querier.order_by(AdminLogModel.created_at.desc()).pagination(page, pageSize)

        logs_list.items = [await AdminLogSerialize.from_orm(log) for log in logs_list.items]
        return logs_list

    @classmethod
    async def oss_list(cls, db: AsyncSession):
        """
        存储设置列表
        :param db:
        :return:
        """
        oss = OSSList.get_all_list()
        res = []
        for item in oss:
            config = await ModelQuerier(db, ConfigsModel).where(ConfigsModel.types == "storage",
                                                                ConfigsModel.key == item["value"]).get_one()
            res_item = {
                "label": item["label"],
                "value": item["value"],
                "status": 1 if config and config.enable else 0,
            }
            res.append(res_item)
        return res

    @classmethod
    async def agreement_list(cls, db: AsyncSession):
        """
        政策协议列表
        :param db:
        :return:
        """
        agree = AgreementType.get_all_list()
        res = []
        for item in agree:
            enum_val = AgreementType(item["value"])
            last_version = await AgreementModel.get_latest_version(db, enum_val)
            status = last_version.status if last_version else 0
            res_item = {
                "id": last_version.id if last_version else None,
                "label": item["label"],
                "title": last_version.title if last_version else item["label"],
                "value": item["value"],
                "status": status,
                "status_text": AgreementStatus.get_label(status),
                "version": last_version.version if last_version else "0.0.0",
                "content": last_version.content if last_version else None,
            }
            res.append(res_item)
        return res

    @classmethod
    async def save_agreement(cls, db: AsyncSession, agree: Agreement):
        """
        保存协议
        :param db: 数据库会话
        :param agree: 协议数据
        :return:
        """
        try:
            enum_val = AgreementType(agree.types)
            last_version = await AgreementModel.get_latest_version(db, enum_val)
            if last_version:
                current_version = version.parse(last_version.version)
                if current_version.micro is not None:
                    # 如果有修订版本，递增修订版本
                    new_version = f"{current_version.major}.{current_version.minor}.{current_version.micro + 1}"
                elif current_version.minor is not None:
                    # 如果有次版本，递增次版本
                    new_version = f"{current_version.major}.{current_version.minor + 1}.0"
                else:
                    # 只有主版本，递增主版本
                    new_version = f"{current_version.major + 1}.0.0"
            else:
                new_version = "1.0.0"

            agreement = AgreementModel(
                types=enum_val,
                title=agree.title,
                content=agree.content,
                status=agree.status,
                version=new_version,
            )
            db.add(agreement)
            await db.commit()
            return True
        except Exception as e:
            cls.logger.error(f"修改协议失败！{str(e)}")
            return False

    @classmethod
    async def update_agreement_statue(cls, db: AsyncSession, a_id: int, status: int):
        """
        更新协议状态
        :param db:
        :param a_id:
        :param status:
        :return:
        """
        try:
            up_agree=await ModelQuerier(db,AgreementModel).where(AgreementModel.id==a_id).update_one(**{"status": status})
            return bool(up_agree)
        except Exception as e:
            cls.logger.error(f"修改协议失败！{str(e)}")
            return False
